package com.farm.controller;


import com.alibaba.fastjson.JSON;
import com.farm.pojo.Partitions;
import com.farm.service.PartitionsService;
import com.farm.common.AppHttpCodeEnum;
import com.farm.common.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author farm
 * @since 2023-12-20
 */
@RestController
@RequestMapping("/partitions")
public class PartitionsController {
    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;
    @Autowired
    private RedisTemplate<Object,Object> template;
    @Autowired
    private PartitionsService partitionsService;
    @GetMapping("/admin/getlist")
    public ResponseResult adminGetList(){
        return ResponseResult.okResult(partitionsService.list());
    }

    @PostMapping("/admin/update")
    public ResponseResult updateUserStatus(@RequestBody Partitions partitions){
        partitionsService.updateById(partitions);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @GetMapping("/getPartitions")
    public List<Map<String,String>> getYiji(){
        List<Partitions> list = partitionsService.list();
        List<Map<String,String>>noList = new ArrayList<>();
        for(Partitions partitions:list){
            Map<String,String> mapJson = new HashMap<>();
            String no = partitions.getId().toString();
            String name = partitions.getName();
            mapJson.put("value",no);
            mapJson.put("label",name);
            noList.add(mapJson);
        }
        return noList;
    }

    @PostMapping("/admin/changeState")
    public ResponseResult changeState(@RequestBody Partitions partitions){
        template.opsForValue().set(partitions.getId() + "", JSON.toJSONString(partitions));
        kafkaTemplate.send("farm.carousel",partitions.getId().toString());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @PostMapping("/admin/delete")
    public ResponseResult delete(@RequestBody Partitions partitions){
        boolean b = partitionsService.removeById(partitions.getId());
        return b?ResponseResult.okResult(AppHttpCodeEnum.SUCCESS):ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
    }

    @PostMapping("/admin/push")
    public ResponseResult upload(@RequestBody Partitions partitions){
        partitionsService.save(partitions);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}

